<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>奖品列表</title>
    <link rel="stylesheet" href="./css/bootstrap.min.css">
    <link rel="stylesheet" href="./css/base.css">
    <style>
        body {
          font-family: Arial, sans-serif;
          padding: 0 30px;
        }
        table {
          height: 300px;
        }
        .table td, .table th{
          border: none;
        }
        .table thead th{
          background-color: #f7f7f7;
          border-bottom: none;
          font-weight: 600;
          font-size: 16px;
          color: #999999;
          height: 80px;
          line-height: 80px;
          padding: 0;
          position: sticky;
          top: 0px;
        }
        .table tbody+tbody{
          border-top: none;
        }
        .prize-table {
          width: 100%;
          height: 100vh;
          overflow-y: auto;
        }
        .prize-table h2{
          background: #fff;
          width: 100%;
          font-weight: 600;
          font-size: 18px;
          color: #000000;
          height: 70px;
          display: flex;
          align-items: center;
          margin-bottom: 0;
        }
        .table-box{
          height: calc(100vh - 140px);
          overflow-y: auto;
        }
        .prize-table th, .prize-table td {
            text-align: center;
            vertical-align: middle;
            padding: 10px;
            height: 50px;
        }
        /* 调整列宽，新增第六列（删除列）宽度为10% */
        .prize-table th:first-child, .prize-table td:first-child,
        .prize-table th:nth-child(3), .prize-table td:nth-child(3),
        .prize-table th:nth-child(5), .prize-table td:nth-child(5) {
            width: 15%;
        }
        .prize-table th:nth-child(4), .prize-table td:nth-child(4) {
            width: 30%;
        }
        .prize-table th:nth-child(2), .prize-table td:nth-child(2) {
            width: 25%;
        }
        .prize-table th:nth-child(6), .prize-table td:nth-child(6) {
            width: 10%; /* 删除功能列宽度 */
        }
        .prize-table td {
          height: 100px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          max-width: 300px;
        }
        .prize-table img{
          width: 76px;
          height: 76px;
          border-radius: 8px;
          object-fit: scale-down;
          border:1px solid #e4e4e4;
        }
        .pagination {
          display: flex;
          justify-content: flex-end;
          margin-top: 18px;
          padding-right: 16px;
        }
        .pagination button {
          margin: 0 5px;
          border-radius: 5px;
          border: 1px solid #007bff;
          background-color: #fff;
          padding: 0px 8px;
          cursor: pointer;
          font-size: 13px;
        }
        .pagination span{
          margin: 0 10px;
          font-size: 14px;
        }
        .pagination input{
          width: 80px;
          text-align: center;
        }
        /* 删除按钮样式 */
        .delete-btn {
          border: none;
          background-color: #dc3545;
          color: white;
          padding: 6px 12px;
          border-radius: 4px;
          cursor: pointer;
          font-size: 13px;
        }
        .delete-btn:hover {
          background-color: #c82333; /*  hover时加深背景色 */
        }
    </style>
</head>
<body>
<div class=" prize-table">
    <h2>奖品列表</h2>
    <div class="table-box">
        <table class="table">
            <thead>
            <tr>
                <th>奖品id</th>
                <th>奖品图</th>
                <th>奖品名</th>
                <th>奖品描述</th>
                <th>奖品价值</th>
                <th>操作</th> <!-- 新增“操作”表头，用于删除功能 -->
            </tr>
            </thead>
            <tbody>
            <tbody id="prizeList">
            <!-- 奖品列表将动态插入这里 -->
            </tbody>
            </tbody>
        </table>
    </div>
    <div class="pagination">
        <button class="btn-outline-primary" onclick="fetchPrizes(1)">首页</button>
        <button class="btn-outline-primary" onclick="previousPage()">上一页</button>
        <span>第 <input type="number" id="pageInput" min="1" value="1" /> 页</span>
        <button class="btn-outline-primary" onclick="nextPage()">下一页</button>
        <button class="btn-outline-primary" onclick="fetchPrizes(totalPages)">尾页</button>
    </div>
</div>
<script src="./js/jquery.min.js"></script>
<script>
    var userToken = localStorage.getItem("user_token");
    var currentPage = 1;
    var pageSize = 10;
    var totalPages;

    // 发送AJAX请求获取奖品列表
    function fetchPrizes(page) {
      if (page < 1) {
        page = 1;
      }
      currentPage = page;
      var dataToSend = {
        currentPage: currentPage,
        pageSize: pageSize
      };
      $.ajax({
          url: '/prize/find-list',
          type: 'GET',
          data: dataToSend,
          headers: {
              "user_token": userToken
          },
          dataType: 'json',
          success: function(result) {
            if (result.code != 200) {
                alert("查询奖品列表失败！" + result.msg);
            } else {
                var prizes = result.data.records;
                var prizeList = $('#prizeList');
                prizeList.empty();
                prizes.forEach(function(prize) {
                    var imageUrl = prize.imageUrl ? prize.imageUrl : '/pic/defaultPrizeImg.png';
                    // 新增删除按钮列，绑定deletePrize函数并传入奖品ID
                    prizeList.append('<tr> ' +
                            '<td>' + prize.prizeId + '</td>' +
                            '<td><img src="' + imageUrl + '" alt="' + prize.prizeName + '" class="prize-image"></td>' +
                            '<td>' + prize.prizeName + '</td>' +
                            '<td>' + prize.description + '</td>' +
                            '<td>' + prize.price + '元</td>' +
                            '<td><button class="delete-btn" onclick="deletePrize(' + prize.prizeId + ')">删除</button></td>' +
                            '</tr>');
                });
                totalPages = Math.ceil(result.data.total / pageSize);
                $('#pageInput').val(currentPage);
              }
          },
          error:function(err){
              console.log(err);
              if(err!=null && err.status==401){
                  alert("用户未登录, 即将跳转到登录页!");
                  window.location.href = "/blogin.html";
                  window.parent.location.href = "/blogin.html";
              }
          }
      });
    }

    // 上一页功能
    function previousPage() {
      if (currentPage > 1) {
        fetchPrizes(currentPage - 1);
      } else {
        alert("已经是第一页");
      }
    }

    // 下一页功能
    function nextPage() {
      if (currentPage < totalPages) {
        fetchPrizes(currentPage + 1);
      } else {
        alert("已经是最后一页");
      }
    }

    // 新增：删除奖品功能
    function deletePrize(prizeId) {
      // 弹窗确认删除，防止误操作
      if (!confirm("确定要删除该奖品吗？删除后不可恢复！")) {
        return; // 取消删除，直接返回
      }

      // 发送删除请求（对应后端@DeleteMapping("/deletePrize")接口）
      $.ajax({
          url: '/deletePrize',
          type: 'DELETE', // 后端为DeleteMapping，请求方式需用DELETE
          data: { id: prizeId }, // 传入奖品ID，参数名与后端@RequestParam("id")对应
          headers: {
              "user_token": userToken // 携带登录令牌，验证权限
          },
          dataType: 'json',
          success: function(result) {
            // 假设后端返回code=200表示删除成功（可根据实际后端返回格式调整）
            if (result == true) {
                alert("奖品删除成功！");
                fetchPrizes(currentPage); // 删除后刷新当前页列表，显示最新数据
            } else {
                alert("奖品删除失败！" + (result.msg || "未知错误"));
            }
          },
          error: function(err) {
              console.log("删除奖品请求错误：", err);
              if (err.status === 401) {
                  alert("用户未登录，无法删除奖品！即将跳转到登录页！");
                  window.location.href = "/blogin.html";
                  window.parent.location.href = "/blogin.html";
              } else {
                  alert("删除奖品时发生错误，请重试！");
              }
          }
      });
    }

    // 页面加载时默认获取第一页奖品
    $(document).ready(function() {
      fetchPrizes(1);
    });

    // 输入框回车跳转指定页
    $('#pageInput').on('keypress', function(e) {
      if (e.key === 'Enter') {
        var page = parseInt(this.value, 10);
        if (!isNaN(page) && page >= 1 && page <= totalPages) {
          fetchPrizes(page);
        }
      }
    });
</script>
</body>
</html>